<?php

namespace Common\Model;
use Think\Model;

class AdminModel extends Model{

    protected $_auto = array(
        array('create_time', NOW_TIME, self::MODEL_INSERT),
        array('reg_time', NOW_TIME, self::MODEL_INSERT),
        array('reg_ip', 'get_client_ip', self::MODEL_INSERT, 'function'),
        array('update_time', NOW_TIME, self::MODEL_BOTH),
        array('status', '1', self::MODEL_INSERT),

    );
    /**
     * 新增或更新
     * 
     * @return boolean fasle 失败 ， int 成功 返回完整的数据
     */
    public function update($data)
    {
        $data = $this->create($data);
        if (empty($data)) {
            return false;
        }
        
        if (empty($data['admin_id'])) {
            $id = $this->add();
            if (! $id) {
                $this->error = '新增管理员出错';
                return false;
            }
        } else {
            $result = $this->where(array( 'admin_id' => $data['admin_id'] ))->save($data);
            if (false === $result) {
                $this->error = '更新管理员出错';
                return false;
            }
        }
        
        return $data;
    }

    /**
     * 用户登录认证
     *
     * @param string $username 用户名
     * @param string $password 用户密码
     * @return integer 登录成功-用户ID，登录失败-错误编号
     */
    public function login($username, $password)
    {
        $admin = $this->where(array( 'user_name' => $username ))->find();
        if (is_array($admin) && $admin['status'] == 1) {
            if (md5($password) === $admin['password']) {
                $auth = array(
                    'admin_id' => $admin['admin_id'],
                    'user_name' => $admin['user_name'],
                    'real_name' => $admin['real_name'],
                    'is_super' => $admin['is_super']
                );
                session('admin_auth', $auth);
                $this->updateLogin($admin['admin_id']);
                return $admin['admin_id'];
            } else {
                return -2;
            }
        } else {
            return -1;
        }
    }

    /**
     * 更新用户登录信息
     * 
     * @param integer $adminID 用户ID
     */
    protected function updateLogin($adminID)
    {
        $data = array(
            'login_time' => NOW_TIME,
            'login_ip' => get_client_ip(),
            'logins' => array( 'exp', '`logins`+1' )
        );
        $this->where(array( 'admin_id' => $adminID ))->save($data);
    }
	
	/**
	 * 注销当前用户
	 * @return void
	 */
	public function logout(){
		session('admin_auth', null);
	}

    /**
     * 管理员的权限规则
     *
     * @param integer $adminID 用户ID
     */
    public function getAdminRule($adminID)
    {
        if (empty($adminID)) {
            return false;
        }
        $result = $this->table('__ADMIN__ a')
            ->join('__ADMIN_GROUP__ g ON a.group_id = g.group_id')
            ->where('a.admin_id = ' . $adminID)
            ->find();
        return empty($result['rules']) ? false : explode(',', $result['rules']);
    }
	
}
